from openai import OpenAI
import requests
import json

def get_weather(location):
    # OpenWeather API key and endpoint
    api_key = "e2cd92b6c1db8c81be27bc1be5f8cc3c"
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    
    # Make request to OpenWeather API
    params = {
        "q": location,
        "appid": api_key,
        "units": "metric"  # For Celsius
    }
    response = requests.get(base_url, params=params)
    weather_data = response.json()
    
    # Extract relevant weather info
    temp = weather_data["main"]["temp"]
    description = weather_data["weather"][0]["description"]
    return f"Temperature: {temp}°C, Conditions: {description}"

def get_forecast(location):
    # OpenWeather API key and endpoint
    api_key = "e2cd92b6c1db8c81be27bc1be5f8cc3c"
    base_url = "http://api.openweathermap.org/data/2.5/forecast"
    
    # Make request to OpenWeather API
    params = {
        "q": location,
        "appid": api_key,
        "units": "metric",
        "cnt": 8  # Get next 24 hours (3 hour steps)
    }
    response = requests.get(base_url, params=params)
    forecast_data = response.json()
    
    # Extract forecast info for next 24 hours
    forecast = []
    for item in forecast_data["list"]:
        temp = item["main"]["temp"]
        description = item["weather"][0]["description"]
        time = item["dt_txt"]
        forecast.append(f"Time: {time}, Temperature: {temp}°C, Conditions: {description}")
    
    return "\n".join(forecast)

def send_messages(messages):
    response = client.chat.completions.create(
        # model="gpt-4o",
        # model="deepseek-chat",
        model="gpt-4o-mini",
        messages=messages,
        tools=tools
    )
    return response.choices[0].message

OPENAI_API_KEY = 'sk-2qHMgOvsbppxJM11ea5oPgWtFtpViu5ghl7QlsLN8CPHdpGn'

client = OpenAI(
  api_key=OPENAI_API_KEY,
  base_url='https://api.fe8.cn/v1' # 默认是https://api.openai.com/v1
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取当地的实时天气, 需要用户提供城市名称,城市要用英文",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name, e.g. London, Paris, Tokyo"
                    }
                },
                "required": ["location"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_forecast",
            "description": "获取当地未来24小时的天气预报, 需要用户提供城市名称,城市要用英文",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name, e.g. London, Paris, Tokyo"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

messages = [{"role": "user", "content": "明天合肥的天气分别怎么样"}]
message = send_messages(messages)
print(f"User>\t {messages[0]['content']}")

if message.tool_calls:
    tool_call = message.tool_calls[0]
    function_name = tool_call.function.name
    function_args = json.loads(tool_call.function.arguments)
    
    if function_name == "get_weather":
        print(f"Function>\t {function_name} with args: {function_args}")
        weather_info = get_weather(function_args["location"])
        messages.append(message)
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": weather_info
        })
    elif function_name == "get_forecast":
        print(f"Function>\t {function_name} with args: {function_args}")
        weather_info = get_forecast(function_args["location"])
        messages.append(message)
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": weather_info
        })
        
    final_response = send_messages(messages)
    print(f"Model>\t {final_response.content}")